package com.atguigu.gulimall.order.service.impl;

import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.entity.OrderReturnReasonEntity;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.order.dao.OrderItemDao;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.service.OrderItemService;

@RabbitListener(queues = {"hello-java-queue"})
@Service("orderItemService")
public class OrderItemServiceImpl extends ServiceImpl<OrderItemDao, OrderItemEntity> implements OrderItemService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderItemEntity> page = this.page(
                new Query<OrderItemEntity>().getPage(params),
                new QueryWrapper<OrderItemEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * queue:声明需要监听的所有队列
     *
     * @param message
     */
    @RabbitHandler
    public void receiveMessage(Message message, OrderReturnReasonEntity content, Channel channel) throws InterruptedException {
        System.out.println("接收到消息....内容：" + content);
        byte[] body = message.getBody();
        //消息头属性信息
        MessageProperties messageProperties = message.getMessageProperties();
//        Thread.sleep(3000);
        System.out.println("消息处理完成=>" + content.getName());
        //channel 按顺序内自增的
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        System.out.println("deliverTag===>" + deliveryTag);
        try {
            if (deliveryTag % 2 == 0) {
                //收货
                channel.basicAck(deliveryTag, false);//签收 消息（货物） multiple:false 非批量签收模式
                System.out.println("签收了货物....." + deliveryTag);
            } else {
                //退货 requeue=false 丢弃 requeue=true 发回服务器，服务器重新入队 重新让消费者消费
//                long deliveryTag, boolean multiple,批量拒绝  boolean requeue 消息是否重新入队
                channel.basicNack(deliveryTag,false,false);
//                long deliveryTag, boolean requeue
//                channel.basicReject();
                System.out.println("没有签收货物..." + deliveryTag);
            }
        } catch (Exception e) {
            //网络中断
        }
    }

    @RabbitHandler
    public void receiveMessage2(OrderEntity content) throws InterruptedException {
        System.out.println("接收到消息....内容：" + content);
    }
}